package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    /**
     *
     * auth:
     * @param id
     */
    @Override
    public void deleteByPrimaryKey(Long id) {
        Menu menu = menuMapper.selectByPrimaryKey(id);
        menuMapper.deleteByPrimaryKey(id);
        List<Menu> children = menu.getChildren();
        if (children!=null){
            for (Menu child : children) {
                deleteByPrimaryKey(child.getId());
            }
        }
        Session session = SecurityUtils.getSubject().getSession();
        session.removeAttribute("MENUS");
    }


    @Override
    public void saveOrUpdate(Menu entity) {
        if (entity.getId() == null) {
            menuMapper.insert(entity);
        } else {
            menuMapper.updateByPrimaryKey(entity);
        }
        Session session = SecurityUtils.getSubject().getSession();
        session.removeAttribute("MENUS");
    }

    @Override
    public Menu selectByPrimaryKey(Long id) {

        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Menu> selectAll() {
        return menuMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer total = menuMapper.query4Count(qo);
        if (total == 0) {
            return PageResult.PAGERESULT_EMPTY;
        }
        return new PageResult(total, menuMapper.query4List(qo));
    }

    @Override
    public List<Menu> getRootMenu() {
        return menuMapper.getRootMenu();
    }

    @Override
    public void selectPermission(List<Menu> menus){
        Iterator<Menu> iterator = menus.iterator();
        Subject subject = SecurityUtils.getSubject();
        while (iterator.hasNext()){
            Menu menu = iterator.next();
            Permission permission = menu.getPermission();
            if(permission != null){
                if (!subject.isPermitted(permission.getResource())) {
                    iterator.remove();
                    continue;
                }
            }
            if(menu.getChildren().size()>0){
                this.selectPermission(menu.getChildren());
            }
        }
    }
}
